package com.test.ssm.controller;

import com.test.ssm.pojo.LoginLog;
import com.test.ssm.pojo.User;
import com.test.ssm.service.LoginLogService;
import com.test.ssm.service.UserService;
import com.test.ssm.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author 徒有琴
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginLogService loginLogService;

    @RequestMapping("gologin.html")
    public String login() {
        return "login";
    }

    @RequestMapping("login.html")
    public String login(String email, String password, Integer type, HttpSession session, Model model) {
        //邮箱，密码不能为空，略
        try {
            User user = userService.doLogin(email, password, type);
            session.setAttribute(Constants.SESSION_USER, user);
            session.setAttribute(Constants.USER_TYPE, type);
            if (type == 1) {//学生，添加登录日志
                LoginLog log=new LoginLog();
                log.setStudentId(user.getId());
                log.setLoginTime(new Date());
                loginLogService.addLog(log);
                return "redirect:student/index.html";
            }else{
                return "redirect:teacher/index.html";
            }
        } catch (Exception e) {//登陆出现teacher异常，返回登陆页面
            e.printStackTrace();
            model.addAttribute("message", e.getMessage());
            return "login";
        }
    }

    @RequestMapping("logout.html")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
